<template>
  <el-drawer v-model="props.visible" direction="ltr" size="60%">
    <template #title>
      <span>发起：{{ props.workflowName }}</span>
    </template>
    <el-card
      shadow="never"
      class="box-card"
      style="margin-top: 10px"
      v-loading="loading"
    >
      <div style="margin-bottom: 15px">
        <el-checkbox
          v-model="withLinkForm"
          label="使用外链表单（仅展示）"
          size="large"
        />
        <el-input
          v-show="withLinkForm"
          placeholder="外链地址"
          v-model="formLink"
        />
        <LinkFormRender :src="formLink" v-show="withLinkForm" />
      </div>
      <el-card
        shadow="never"
        class="box-card"
        style="margin-top: 10px"
        v-loading="loading"
      >
        <FormRender ref="formRenderRef" @form-change="onFormChange()" />
      </el-card>
    </el-card>
    <br />
    <ForecastHandleUser ref="forecastHandleUserRef" />

    <div style="text-align: right">
      <br />
      <el-button type="primary" @click="onSubmit(true)">提 交</el-button>
      <el-button type="success" @click="onSubmit(false)">保存草稿</el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { defineProps, watch, ref, nextTick, onMounted } from "vue";
import { useWorkTaskStore } from "@/stores/workTask";
import { useDynamicFormDesignStore } from "@/stores/dynamicFormDesign";
import { useOrganisationUserStore } from "@/stores/organisationUser";
import ForecastHandleUser from "@/components/WorkflowDesign/FlowSimulations/ForecastHandleUser.vue";
import FormRender from "@/components/WorkflowDesign/formComponents/FormRender.vue";
import LinkFormRender from "@/components/WorkflowDesign/formComponents/LinkFormRender.vue";

const props = defineProps({
  visible: {
    default: false,
  },
  workflowId: {
    default: "",
  },
  workflowName: {
    default: "",
  },
  workflowVersion: {
    default: 0,
  },
});
const emit = defineEmits(["update:visible", "closed"]);
const loading = ref(false);

const formRenderRef = ref(null);
const forecastHandleUserRef = ref(null);
const dynamicFormDesignStore = useDynamicFormDesignStore();
const organisationUserStore = useOrganisationUserStore();

const workTaskStore = useWorkTaskStore();
const withLinkForm = ref(false);
const formLink = ref("");

watch(withLinkForm, () => {
  if (!withLinkForm.value) {
    formLink.value = "";
  }
});
watch(
  () => props.workflowId,
  () => {
    load();
  }
);

const load = async () => {
  await nextTick();
  formLink.value = "";
  withLinkForm.value = false;
  setTimeout(() => {
    formRenderRef.value.setDesignContent("", "");
    formRenderRef.value.setFormData({});
    getActiveFormDesignVersionByWorkflowId(props.workflowId);
    onFormChange();
  }, 500);
};

const getActiveFormDesignVersionByWorkflowId = async (workflowId) => {
  if (!workflowId || workflowId.length == 0) return;
  loading.value = true;
  const res =
    await dynamicFormDesignStore.getActiveFormDesignVersionByWorkflowId({
      workflowId: workflowId,
    });
  if (res) {
    formRenderRef.value.setDesignContent(
      res.designContent,
      res.designFramework
    );
  }
  loading.value = false;
};

const onFormChange = async () => {
  formRenderRef.value.validateForm(async (valid) => {
    if (valid) {
      let data = await formRenderRef.value.getFormData();
      const workflowInfo = {
        workflowId: props.workflowId,
        versionNo: props.workflowVersion,
        formData: data,
      };
      getForecastNodeUsers4Workflow(workflowInfo);
    }
  });
};
const getForecastNodeUsers4Workflow = (workflowInfo) => {
  forecastHandleUserRef.value.getForecastNodeUsers4Workflow(workflowInfo);
};

const onSubmit = async (isSubmit) => {
  formRenderRef.value.validateForm(async (valid) => {
    if (!valid) return;
    loading.value = true;

    const workTaskForm = {
      id: "",
      createdUserId: organisationUserStore.getCurrentUser?.id,
      entityFullName: "dynamicForm",
      entityKeyValue: new Date().getTime().toString(),
      formData: await formRenderRef.value.getFormData(),
      workTaskStatus: "",
      name: props.workflowName,
      workflowId: {
        versionNo: props.workflowVersion,
        id: props.workflowId,
      },
      formLink: formLink.value,
    };

    let res = await workTaskStore.createWorkTask(workTaskForm);
    const data = {
      workTaskId: res.id,
    };
    if (isSubmit) {
      await workTaskStore.startWorkTask(data);
    }

    loading.value = false;
    onClose();
  });
};

const onClose = () => {
  emit("closed");
};
onMounted(() => {});
</script>

<style lang="less" scoped>
.el-col {
  padding: 5px;
}
.el-col .el-card {
  cursor: pointer;
}
</style>
